/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 字段管理模块
 * 尊重劳动成果是一种美德
 */

let currentFieldData = [];
let isFieldLoading = false;

// 页面加载后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('field-manage.js 已加载');
    
    // 监听TAB切换，切换到字段管理TAB时加载表单选择器
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                const target = mutation.target;
                if (target.id === 'field-manage' && target.classList.contains('active')) {
                    loadFieldSchemaSelector();
                }
            }
        });
    });
    
    const fieldManageTab = document.getElementById('field-manage');
    if (fieldManageTab) {
        observer.observe(fieldManageTab, { attributes: true });
        // 如果已经是激活状态，立即加载
        if (fieldManageTab.classList.contains('active')) {
            setTimeout(() => loadFieldSchemaSelector(), 500);
        }
    }
});

// 加载表单选择器
function loadFieldSchemaSelector() {
    const select = document.getElementById('field-schema-select');
    if (!select) {
        console.error('字段管理表单选择器元素未找到');
        return;
    }
    
    console.log('开始加载字段管理表单选择器');
    
    fetch('api/get_schemas.php')
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.schemas) {
                let html = '';
                data.schemas.forEach((schema, index) => {
                    const selected = index === 0 ? 'selected' : '';
                    html += `<option value="${schema.schema_key}" ${selected}>${schema.schema_name}</option>`;
                });
                select.innerHTML = html;
                console.log('字段管理表单选择器加载成功，共', data.schemas.length, '个表单');
                
                // 绑定change事件：切换表单后隐藏之前的结果
                select.onchange = function() {
                    const resultsDiv = document.getElementById('field-results');
                    const summaryDiv = document.getElementById('field-summary');
                    if (resultsDiv) resultsDiv.style.display = 'none';
                    if (summaryDiv) summaryDiv.style.display = 'none';
                    hideBatchButtons();
                };
            } else {
                select.innerHTML = '<option value="default">默认表单</option>';
            }
        })
        .catch(error => {
            console.error('加载字段管理表单选择器失败:', error);
            select.innerHTML = '<option value="default">默认表单</option>';
        });
}

// 初始化字段管理界面
function initFieldManageInterface() {
    const fieldSection = document.getElementById('field-manage');
    if (!fieldSection) return;
    
    // 检查是否已经初始化
    if (fieldSection.querySelector('.field-panel')) return;
    
    const html = `
        <div class="field-panel">
            <div class="field-actions">
                <div class="action-container">
                    <button id="get-fields-btn" class="btn btn-primary" onclick="fetchAllFields()">
                        <span id="get-fields-btn-text">获取所有字段</span>
                    </button>
                    <select id="field-filter" onchange="filterFields()" style="display:none;">
                        <option value="all">全部字段</option>
                        <option value="system">系统字段</option>
                        <option value="main">主表字段</option>
                        <option value="main_image">主表图片</option>
                        <option value="main_attachment">主表附件</option>
                        <option value="child_table">子表</option>
                        <option value="child_field">子表业务</option>
                        <option value="child_image">子表图片</option>
                        <option value="child_attachment">子表附件</option>
                    </select>
                    <button id="select-all-btn" class="btn btn-secondary" onclick="toggleSelectAll()" style="display:none;">
                        <span id="select-all-text">全选</span>
                    </button>
                    <button id="batch-action-btn" class="btn btn-secondary" onclick="performBatchAction()" style="display:none;">
                        <span>生成SQL文件</span>
                    </button>
                </div>
            </div>
            
            <div id="field-status" class="field-status" style="display:none;">
                正在获取字段信息...
            </div>
            
            <div id="field-summary" class="field-summary" style="display:none;">
                <!-- 字段统计信息将显示在这里 -->
            </div>
            
            <div id="field-results" class="field-results" style="display:none;">
                <!-- 字段详情将显示在这里 -->
            </div>
        </div>
    `;
    
    fieldSection.innerHTML = fieldSection.innerHTML.replace('<!-- 字段管理功能将由JavaScript动态加载 -->', html);
    console.log('字段管理界面初始化完成');
}

// 获取所有字段
function fetchAllFields() {
    if (isFieldLoading) return;
    
    console.log('开始获取字段数据...');
    updateFieldButton(true);
    isFieldLoading = true;
    
    // 获取选中的表单
    const schemaSelect = document.getElementById('field-schema-select');
    if (!schemaSelect || !schemaSelect.value) {
        console.error('请先选择表单');
        updateFieldButton(false);
        isFieldLoading = false;
        return;
    }
    const schemaKey = schemaSelect.value;
    
    // 使用数据查询接口获取一条示例数据来提取字段
    // 不限制日期，获取最新的一条数据
    const today = new Date();
    const oneYearAgo = new Date();
    oneYearAgo.setFullYear(today.getFullYear() - 1);
    
    const params = new URLSearchParams({
        action: 'query_data',
        schema_key: schemaKey,
        date_type: 'range',
        start_date: oneYearAgo.toISOString().split('T')[0],
        end_date: today.toISOString().split('T')[0],
        data_limit: 1,
        sort_order: 'desc'
    });
    
    fetch(`api/data_query.php?${params.toString()}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => {
        console.log('字段获取响应状态:', response.status);
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('服务器返回非 JSON 数据');
        }
        
        return response.text();
    })
    .then(text => {
        console.log('字段获取原始响应:', text.substring(0, 200));
        
        if (!text || text.trim() === '') {
            throw new Error('服务器返回空响应');
        }
        
        try {
            return JSON.parse(text);
        } catch (parseError) {
            console.error('JSON解析错误:', parseError.message);
            throw new Error(`JSON解析失败: ${parseError.message}`);
        }
    })
    .then(data => {
        console.log('字段数据响应:', data);
        if (data.success && data.data && data.data.length > 0) {
            // 提取字段信息
            const sampleRecord = data.data[0];
            extractFieldsFromSample(sampleRecord);
        } else {
            console.error('字段获取失败：该表单没有数据，无法提取字段信息');
            alert('该表单没有数据，无法提取字段信息。请先在氚云系统中创建至少一条数据。');
        }
    })
    .catch(error => {
        console.error('字段获取异常:', error);
    })
    .finally(() => {
        updateFieldButton(false);
        isFieldLoading = false;
    });
}

// 从示例记录中提取字段信息
function extractFieldsFromSample(sampleRecord) {
    const fields = [];
    const addedFields = new Set(); // 优化：使用Set加速查找
    
    // 系统字段
    const systemFields = ['id', 'title', 'created_time'];
    systemFields.forEach(field => {
        if (sampleRecord.hasOwnProperty(field)) {
            const sampleValue = sampleRecord[field];
            fields.push({
                field_code: field,
                field_name: getFieldDisplayName(field, null),
                field_type: getFieldType(sampleValue),
                is_system: true,
                is_image: false,
                is_attachment: false,
                sample_value: sampleValue,
                display_value: formatSampleValue(sampleValue)
            });
            addedFields.add(field);
        }
    });
    
    // 图片字段
    if (sampleRecord.image_fields && Array.isArray(sampleRecord.image_fields)) {
        sampleRecord.image_fields.forEach(imageField => {
            // 清理图片字段代码
            const cleanImageFieldCode = String(imageField.field_code).replace(/Object$|Array$|String$|Number$|Boolean$|Date$|Reference$/i, '');
            
            // 检查是否已添加
            if (!addedFields.has(cleanImageFieldCode)) {
                fields.push({
                    field_code: cleanImageFieldCode,
                    field_name: getFieldDisplayName(cleanImageFieldCode, null),
                    field_type: 'json',
                    is_system: false,
                    is_image: true,
                    is_attachment: false,
                    sample_value: imageField.value,
                    display_value: formatSampleValue(imageField.value)
                });
                addedFields.add(cleanImageFieldCode);
            }
        });
    }
    
    // 所有业务字段（包括子表字段）
    if (sampleRecord.all_fields && typeof sampleRecord.all_fields === 'object') {
        for (const fieldCode in sampleRecord.all_fields) {
            const field = sampleRecord.all_fields[fieldCode];
            
            // 跳过已添加的字段（优化：使用Set查找）
            if (addedFields.has(fieldCode)) {
                continue;
            }
            
            // 清理字段代码，移除可能的后缀（包括更多类型）
            const cleanFieldCode = String(fieldCode).replace(/Object$|Array$|String$|Number$|Boolean$|Date$|Reference$/i, '');
            
            // 跳过已存在的清理后字段（避免重复）
            if (addedFields.has(cleanFieldCode)) {
                console.log('跳过重复字段:', fieldCode, '（清理后与已存在字段重复：', cleanFieldCode, '）');
                continue;
            }
            
            const fieldSampleValue = field.raw_value;
            const fieldDisplayValue = field.display_value;
            
            // 判断是否是子表字段（D开头40位十六进制）
            const isChildTable = /^D[0-9a-fA-F]{39}$/.test(cleanFieldCode);
            
            // 如果是子表字段，提取子表内部的业务字段
            if (isChildTable && Array.isArray(fieldSampleValue) && fieldSampleValue.length > 0) {
                console.log('发现子表字段:', cleanFieldCode, '包含', fieldSampleValue.length, '行数据');
                
                // 从子表的第一行数据中提取字段信息
                const childTableRow = fieldSampleValue[0];
                if (childTableRow && typeof childTableRow === 'object') {
                    for (const childFieldCode in childTableRow) {
                        // 跳过系统字段
                        if (['ObjectId', 'RowNumber'].includes(childFieldCode)) {
                            continue;
                        }
                        
                        // 构建子表字段的完整代码：子表代码.字段代码
                        const fullChildFieldCode = `${cleanFieldCode}.${childFieldCode}`;
                        
                        // 检查是否已存在
                        if (fields.some(f => f.field_code === fullChildFieldCode)) {
                            continue;
                        }
                        
                        const childFieldValue = childTableRow[childFieldCode];
                        
                        // 判断子表字段是否是图片或附件
                        const isChildImage = isImageField(childFieldValue, childFieldCode);
                        const isChildAttachment = isAttachmentField(childFieldValue, childFieldCode);
                        
                        fields.push({
                            field_code: fullChildFieldCode,
                            field_name: `${cleanFieldCode}.${childFieldCode}`,
                            field_type: getFieldType(childFieldValue),
                            is_system: false,
                            is_image: isChildImage,
                            is_attachment: isChildAttachment,
                            is_child_table: false,
                            is_child_table_field: true, // 标记为子表内部字段
                            parent_table: cleanFieldCode, // 记录父子表代码
                            sample_value: childFieldValue,
                            display_value: formatSampleValue(childFieldValue)
                        });
                    }
                }
            }
            
            // 添加主字段（包括子表字段本身）
            const newField = {
                field_code: cleanFieldCode, // 使用清理后的字段代码
                field_name: getFieldDisplayName(cleanFieldCode, null), // 不传递样例值，只使用字段代码
                field_type: getFieldType(fieldSampleValue),
                is_system: isSystemField(cleanFieldCode),
                is_image: field.is_image || false,
                is_attachment: field.is_attachment || false,
                is_child_table: isChildTable, // 标记是否为子表字段
                is_child_table_field: false,
                sample_value: fieldSampleValue,
                display_value: fieldDisplayValue || formatSampleValue(fieldSampleValue)
            };
            
            fields.push(newField);
            addedFields.add(cleanFieldCode); // 记录已添加的字段
        }
    }
    
    // 按字段类型和名称排序
    fields.sort((a, b) => {
        // 系统字段优先
        if (a.is_system !== b.is_system) {
            return a.is_system ? -1 : 1;
        }
        // 然后按字段代码排序
        return a.field_code.localeCompare(b.field_code);
    });
    
    currentFieldData = fields;
    console.log('提取到字段数据:', fields);
    
    // 显示字段信息
    displayFieldSummary();
    displayFieldDetails();
}

// 显示字段摘要
function displayFieldSummary() {
    const summaryDiv = document.getElementById('field-summary');
    if (!summaryDiv) return;
    
    const totalCount = currentFieldData.length;
    const systemCount = currentFieldData.filter(f => f.is_system).length;
    const childTableCount = currentFieldData.filter(f => f.is_child_table).length;
    const childTableFieldCount = currentFieldData.filter(f => f.is_child_table_field).length;
    const imageCount = currentFieldData.filter(f => f.is_image).length;
    const attachmentCount = currentFieldData.filter(f => f.is_attachment).length;
    const businessCount = totalCount - systemCount - childTableCount - childTableFieldCount;
    
    const html = `
        <div class="summary-card">
            <h4>字段统计</h4>
            <div class="stats-grid">
                <div class="stat-item">
                    <span class="stat-number">${totalCount}</span>
                    <span class="stat-label">总字段数</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${systemCount}</span>
                    <span class="stat-label">系统字段</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${businessCount}</span>
                    <span class="stat-label">业务字段</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${childTableCount}</span>
                    <span class="stat-label">子表</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${childTableFieldCount}</span>
                    <span class="stat-label">子表字段</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${imageCount}</span>
                    <span class="stat-label">图片字段</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${attachmentCount}</span>
                    <span class="stat-label">附件字段</span>
                </div>
            </div>
        </div>
    `;
    
    summaryDiv.innerHTML = html;
    summaryDiv.style.display = 'block';
}

// 显示字段详情
function displayFieldDetails() {
    const resultsDiv = document.getElementById('field-results');
    if (!resultsDiv) return;
    
    if (currentFieldData.length === 0) {
        resultsDiv.innerHTML = '<div class="no-data">暂无字段数据</div>';
        return;
    }
    
    let html = `
        <div class="field-table-container">
            <div style="overflow-x: auto;">
                <table class="field-table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="select-all-checkbox" onchange="handleSelectAllChange()"> 选择</th>
                            <th>字段代码</th>
                            <th>字段名称</th>
                            <th>数据类型</th>
                            <th>字段分类</th>
                        </tr>
                    </thead>
                    <tbody>
    `;
    
    currentFieldData.forEach((field, index) => {
        const categoryTags = [];
        if (field.is_system) {
            categoryTags.push('<span class="field-tag system">系统字段</span>');
        } else if (field.is_child_table_field) {
            categoryTags.push('<span class="field-tag child-field">子表业务</span>');
        } else if (field.is_child_table) {
            categoryTags.push('<span class="field-tag child-table">子表字段</span>');
        } else {
            categoryTags.push('<span class="field-tag business">主表字段</span>');
        }
        
        if (field.is_image) categoryTags.push('<span class="field-tag image">图片</span>');
        if (field.is_attachment) categoryTags.push('<span class="field-tag attachment">附件</span>');
        
        html += `
            <tr>
                <td><input type="checkbox" class="field-checkbox" data-field-code="${field.field_code}" onchange="handleFieldSelection()"></td>
                <td><code>${field.field_code}</code></td>
                <td>${field.field_name}</td>
                <td><span class="type-badge">${field.field_type}</span></td>
                <td>${categoryTags.join(' ')}</td>
            </tr>
        `;
    });
    
    html += `
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    resultsDiv.innerHTML = html;
    resultsDiv.style.display = 'block';
    
    // 显示批量操作按钮
    showBatchButtons();
}

// 更新字段按钮状态
function updateFieldButton(loading) {
    const btn = document.getElementById('get-fields-btn');
    const btnText = document.getElementById('get-fields-btn-text');
    
    if (btn && btnText) {
        if (loading) {
            btn.disabled = true;
            btn.classList.add('loading');
            btnText.textContent = '正在获取...';
        } else {
            btn.disabled = false;
            btn.classList.remove('loading');
            btnText.textContent = '获取所有字段';
        }
    }
}

// 显示批量操作按钮
function showBatchButtons() {
    const selectAllBtn = document.getElementById('select-all-btn');
    const batchActionBtn = document.getElementById('batch-action-btn');
    const fieldFilter = document.getElementById('field-filter');
    
    if (selectAllBtn) selectAllBtn.style.display = 'inline-block';
    if (batchActionBtn) batchActionBtn.style.display = 'inline-block';
    if (fieldFilter) fieldFilter.style.display = 'inline-block';
}

// 隐藏批量操作按钮
function hideBatchButtons() {
    const selectAllBtn = document.getElementById('select-all-btn');
    const batchActionBtn = document.getElementById('batch-action-btn');
    const fieldFilter = document.getElementById('field-filter');
    
    if (selectAllBtn) selectAllBtn.style.display = 'none';
    if (batchActionBtn) batchActionBtn.style.display = 'none';
    if (fieldFilter) fieldFilter.style.display = 'none';
}

// 全选/反选切换
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('select-all-checkbox');
    const fieldCheckboxes = document.querySelectorAll('.field-checkbox');
    const selectAllText = document.getElementById('select-all-text');
    
    if (!selectAllCheckbox || !fieldCheckboxes.length) return;
    
    const isAllSelected = Array.from(fieldCheckboxes).every(cb => cb.checked);
    
    if (isAllSelected) {
        // 当前全部选中，执行反选
        fieldCheckboxes.forEach(cb => cb.checked = false);
        selectAllCheckbox.checked = false;
        selectAllText.textContent = '全选';
    } else {
        // 执行全选
        fieldCheckboxes.forEach(cb => cb.checked = true);
        selectAllCheckbox.checked = true;
        selectAllText.textContent = '反选';
    }
    
    updateBatchButtonState();
}

// 处理全选复选框变化
function handleSelectAllChange() {
    const selectAllCheckbox = document.getElementById('select-all-checkbox');
    const fieldCheckboxes = document.querySelectorAll('.field-checkbox');
    const selectAllText = document.getElementById('select-all-text');
    
    if (!selectAllCheckbox || !fieldCheckboxes.length) return;
    
    fieldCheckboxes.forEach(cb => cb.checked = selectAllCheckbox.checked);
    
    if (selectAllCheckbox.checked) {
        selectAllText.textContent = '反选';
    } else {
        selectAllText.textContent = '全选';
    }
    
    updateBatchButtonState();
}

// 处理字段选择变化
function handleFieldSelection() {
    const selectAllCheckbox = document.getElementById('select-all-checkbox');
    const fieldCheckboxes = document.querySelectorAll('.field-checkbox');
    const selectAllText = document.getElementById('select-all-text');
    
    if (!selectAllCheckbox || !fieldCheckboxes.length) return;
    
    const checkedCount = Array.from(fieldCheckboxes).filter(cb => cb.checked).length;
    const totalCount = fieldCheckboxes.length;
    
    if (checkedCount === totalCount) {
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = false;
        selectAllText.textContent = '反选';
    } else if (checkedCount === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
        selectAllText.textContent = '全选';
    } else {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = true;
        selectAllText.textContent = '全选';
    }
    
    updateBatchButtonState();
}

// 更新批量操作按钮状态
function updateBatchButtonState() {
    const fieldCheckboxes = document.querySelectorAll('.field-checkbox');
    const batchActionBtn = document.getElementById('batch-action-btn');
    
    if (!batchActionBtn) return;
    
    const checkedCount = Array.from(fieldCheckboxes).filter(cb => cb.checked).length;
    
    if (checkedCount > 0) {
        batchActionBtn.disabled = false;
        batchActionBtn.innerHTML = `<span>生成SQL文件 (${checkedCount})</span>`;
    } else {
        batchActionBtn.disabled = true;
        batchActionBtn.innerHTML = '<span>生成SQL文件</span>';
    }
}

// 执行批量操作
function performBatchAction() {
    const fieldCheckboxes = document.querySelectorAll('.field-checkbox:checked');
    
    if (fieldCheckboxes.length === 0) {
        alert('请先选择要生成SQL的字段');
        return;
    }
    
    // 防止重复提交
    if (isFieldLoading) {
        alert('正在生成中，请勿重复操作');
        return;
    }
    
    const selectedFields = Array.from(fieldCheckboxes).map(cb => {
        const fieldCode = cb.getAttribute('data-field-code');
        return currentFieldData.find(field => field.field_code === fieldCode);
    }).filter(field => field);
    
    // 显示确认对话框
    showConfirmDialog(selectedFields);
}

// 显示确认对话框
function showConfirmDialog(selectedFields) {
    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
        display: flex;
        justify-content: center;
        align-items: center;
    `;
    
    // 统计信息
    const systemCount = selectedFields.filter(f => f.is_system).length;
    const businessCount = selectedFields.filter(f => !f.is_system && !f.is_child_table && !f.is_child_table_field).length;
    const childTableCount = selectedFields.filter(f => f.is_child_table).length;
    const childFieldCount = selectedFields.filter(f => f.is_child_table_field).length;
    const imageCount = selectedFields.filter(f => f.is_image).length;
    const attachmentCount = selectedFields.filter(f => f.is_attachment).length;
    
    // 创建对话框
    const dialog = document.createElement('div');
    dialog.style.cssText = `
        background: white;
        border-radius: 8px;
        padding: 30px;
        max-width: 600px;
        width: 90%;
        max-height: 80vh;
        overflow-y: auto;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    `;
    
    dialog.innerHTML = `
        <h3 style="margin: 0 0 20px 0; color: #333; font-size: 18px;  padding-bottom: 10px;">
            确认生成SQL文件
        </h3>
        
        <div style="margin-bottom: 20px;">
            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 20px;">
                <div style="background: #f8f9fa; padding: 10px; border-radius: 4px; text-align: center;">
                    <div style="color: #666; font-size: 11px; margin-bottom: 4px;">总字段数</div>
                    <div style="color: #333; font-size: 20px; font-weight: bold;">${selectedFields.length}</div>
                </div>
                <div style="background: #e3f2fd; padding: 10px; border-radius: 4px; text-align: center;">
                    <div style="color: #666; font-size: 11px; margin-bottom: 4px;">系统字段</div>
                    <div style="color: #1976d2; font-size: 20px; font-weight: bold;">${systemCount}</div>
                </div>
                <div style="background: #e8f5e8; padding: 10px; border-radius: 4px; text-align: center;">
                    <div style="color: #666; font-size: 11px; margin-bottom: 4px;">业务字段</div>
                    <div style="color: #2e7d32; font-size: 20px; font-weight: bold;">${businessCount}</div>
                </div>
                <div style="background: #fff3e0; padding: 10px; border-radius: 4px; text-align: center;">
                    <div style="color: #666; font-size: 11px; margin-bottom: 4px;">子表字段</div>
                    <div style="color: #e65100; font-size: 20px; font-weight: bold;">${childTableCount}</div>
                </div>
                <div style="background: #fce4ec; padding: 10px; border-radius: 4px; text-align: center;">
                    <div style="color: #666; font-size: 11px; margin-bottom: 4px;">子表业务</div>
                    <div style="color: #c2185b; font-size: 20px; font-weight: bold;">${childFieldCount}</div>
                </div>
                <div style="background: #f3e5f5; padding: 10px; border-radius: 4px; text-align: center;">
                    <div style="color: #666; font-size: 11px; margin-bottom: 4px;">图片/附件</div>
                    <div style="color: #7b1fa2; font-size: 20px; font-weight: bold;">${imageCount + attachmentCount}</div>
                </div>
            </div>
            
            <p style="color: #666; font-size: 14px; margin: 0 0 10px 0;">
                将为选中的 ${selectedFields.length} 个字段生成SQL数据库结构文件
            </p>
            
            <div style="max-height: 200px; overflow-y: auto; background: #f8f9fa; padding: 15px; border-radius: 4px; border: 1px solid #e9ecef;">
                <div style="color: #666; font-size: 12px; margin-bottom: 10px; font-weight: bold;">包含字段：</div>
                ${selectedFields.map(f => `
                    <div style="padding: 4px 0; border-bottom: 1px solid #e9ecef; font-size: 13px;">
                        <code style="background: white; padding: 2px 6px; border-radius: 3px; color: #d63384;">${f.field_code}</code>
                        <span style="color: #666; margin-left: 10px;">${f.field_name}</span>
                    </div>
                `).join('')}
            </div>
        </div>
        
        <div style="display: flex; gap: 10px; justify-content: flex-end;">
            <button id="cancel-generate" class="btn btn-secondary" style="padding: 10px 24px;">
                取消
            </button>
            <button id="confirm-generate" class="btn btn-primary" style="padding: 10px 24px;">
                下载
            </button>
        </div>
    `;
    
    overlay.appendChild(dialog);
    document.body.appendChild(overlay);
    
    // 绑定事件
    document.getElementById('cancel-generate').onclick = function() {
        document.body.removeChild(overlay);
    };
    
    document.getElementById('confirm-generate').onclick = function() {
        document.body.removeChild(overlay);
        generateSQLFromFields(selectedFields);
    };
    
    // 点击遮罩层关闭
    overlay.onclick = function(e) {
        if (e.target === overlay) {
            document.body.removeChild(overlay);
        }
    };
}

// 缺失的辅助函数

// 更新字段状态显示
function updateFieldStatus(message, type) {
    const statusElement = document.getElementById('field-status');
    if (statusElement) {
        statusElement.textContent = message;
        statusElement.className = 'field-status ' + (type || 'info');
        statusElement.style.display = 'block';
        console.log('字段状态更新:', message, type);
    }
}

// 获取字段显示名称 - 只对系统字段提供中文名称
function getFieldDisplayName(fieldCode, sampleValue) {
    // 清理字段代码，移除可能的后缀
    const cleanFieldCode = String(fieldCode).replace(/Object$|Array$|String$|Number$/i, '');
    console.log('原始字段代码:', fieldCode, '清理后:', cleanFieldCode);
    
    // 系统字段映射表 - 只有这些提供中文名称
    const systemFieldNames = {
        'id': 'ID',
        'ObjectId': '对象ID', 
        'Name': '名称',
        'title': '标题',
        'created_time': '创建时间',
        'CreatedBy': '创建人',
        'CreatedTime': '创建时间',
        'ModifiedBy': '修改人', 
        'ModifiedTime': '修改时间',
        'Status': '状态',
        'OwnerId': '拥有者',
        'OwnerDeptId': '拥有部门',
        'WorkflowInstanceId': '工作流实例',
        'SeqNo': '序列号',
        'IconId': '图标ID',
        'SchemaCode': '表单编码',
        'BizObjectId': '业务对象ID',
        'ParentObjectId': '父对象ID',
        'IsDeleted': '是否删除'
    };
    
    // 如果是已知的系统字段，返回中文名称
    if (systemFieldNames[cleanFieldCode]) {
        console.log('系统字段映射:', cleanFieldCode, '->', systemFieldNames[cleanFieldCode]);
        return systemFieldNames[cleanFieldCode];
    }
    
    // 其他所有字段（业务、图片、附件）都保持原始字段代码（清理后的）
    console.log('非系统字段，使用清理后代码:', cleanFieldCode);
    return cleanFieldCode;
}

// 获取字段数据类型
function getFieldType(value) {
    if (value === null || value === undefined) {
        return 'null';
    }
    
    if (typeof value === 'string') {
        if (value === '') return 'string';
        
        // 检查是否是日期格式
        if (/^\d{4}-\d{2}-\d{2}/.test(value)) {
            return 'datetime';
        }
        
        // 检查是否是数字字符串
        if (/^\d+$/.test(value)) {
            return 'string';
        }
        
        // 检查是否是JSON
        try {
            JSON.parse(value);
            return 'json';
        } catch (e) {
            return 'string';
        }
    }
    
    if (typeof value === 'number') {
        return Number.isInteger(value) ? 'integer' : 'decimal';
    }
    
    if (typeof value === 'boolean') {
        return 'boolean';
    }
    
    if (Array.isArray(value)) {
        return 'array';
    }
    
    if (typeof value === 'object') {
        return 'object';
    }
    
    return 'unknown';
}

// 格式化示例值
function formatSampleValue(value) {
    if (value === null || value === undefined) {
        return '空';
    }
    
    if (typeof value === 'string') {
        if (value === '') return '空字符串';
        
        // 限制显示长度
        if (value.length > 100) {
            return value.substring(0, 100) + '...';
        }
        
        return value;
    }
    
    if (typeof value === 'object') {
        return JSON.stringify(value, null, 2);
    }
    
    return String(value);
}

// 判断是否是系统字段
function isSystemField(fieldCode) {
    const systemFields = ['id', 'ObjectId', 'SeqNo', 'title', 'created_time', 'Name', 'CreatedBy', 'CreatedTime', 'ModifiedTime', 'Status'];
    return systemFields.includes(fieldCode);
}

// 转义HTML
function escapeHtml(text) {
    if (typeof text !== 'string') {
        return String(text);
    }
    
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 截断文本
function truncateText(text, maxLength) {
    if (typeof text !== 'string') {
        text = String(text);
    }
    
    if (text.length <= maxLength) {
        return text;
    }
    
    return text.substring(0, maxLength) + '...';
}

// 根据选中字段生成SQL文件
function generateSQLFromFields(selectedFields) {
    // 获取当前时间作为文件名
    const now = new Date();
    const timestamp = now.toISOString().replace(/[:\-T]/g, '').split('.')[0];
    const fileName = `custom_database_${timestamp}.sql`;
    
    // 生成SQL内容
    const sqlContent = generateSQLContent(selectedFields);
    
    // 创建下载链接
    const blob = new Blob([sqlContent], { type: 'text/sql;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    
    // 创建临时下载链接
    const downloadLink = document.createElement('a');
    downloadLink.href = url;
    downloadLink.download = fileName;
    downloadLink.style.display = 'none';
    
    // 执行下载
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    
    // 清理内存
    URL.revokeObjectURL(url);
    
    // 显示生成结果
    showGenerationResult(selectedFields, fileName);
}

// 生成SQL内容
function generateSQLContent(fields) {
    const timestamp = new Date().toLocaleString('zh-CN');
    const mainTableName = 'h3yun_orders';
    
    // 去重系统字段：保留created_time，移除CreatedTime
    const dedupedFields = [];
    const seenCodes = new Set();
    
    fields.forEach(field => {
        const code = field.field_code.toLowerCase();
        // 跳过CreatedTime，保留created_time
        if (code === 'createdtime' && seenCodes.has('created_time')) {
            return;
        }
        if (code === 'created_time') {
            seenCodes.add('created_time');
        }
        dedupedFields.push(field);
    });
    
    // 分离主表字段和子表字段
    const mainFields = dedupedFields.filter(f => !f.is_child_table && !f.is_child_table_field);
    const childTables = {};
    
    // 按子表分组子表字段
    dedupedFields.filter(f => f.is_child_table_field).forEach(field => {
        const parentTable = field.parent_table;
        if (!childTables[parentTable]) {
            childTables[parentTable] = [];
        }
        childTables[parentTable].push(field);
    });
    
    let sql = `-- ===========================================\n`;
    sql += `-- 氚云数据库结构文件（可直接执行）\n`;
    sql += `-- 生成时间: ${timestamp}\n`;
    sql += `-- 主表字段: ${mainFields.length}\n`;
    sql += `-- 子表数量: ${Object.keys(childTables).length}\n`;
    sql += `-- 生成来源: 字段管理模块\n`;
    sql += `-- ===========================================\n\n`;
    
    // 生成主表
    sql += generateMainTable(mainFields, mainTableName);
    
    // 生成子表
    for (const [parentCode, childFields] of Object.entries(childTables)) {
        sql += generateChildTable(childFields, parentCode, mainTableName);
    }
    
    // 生成索引
    sql += generateIndexes(mainFields, mainTableName);
    
    // 生成视图（可选）
    sql += generateViews(mainFields, childTables, mainTableName);
    
    // 生成查询示例
    sql += generateQueryExamples(mainFields, mainTableName);
    
    return sql;
}

// 生成列定义
function generateColumnDefinition(field) {
    const columnName = '`' + field.field_code + '`';
    const comment = `'${field.field_name.replace(/'/g, "\\'")}'`;
    
    let dataType = '';
    let nullable = 'NULL';
    let defaultValue = '';
    let extraConstraints = '';
    
    // 智能识别时间字段
    const isTimeField = /time|date/i.test(field.field_code) || /time|date/i.test(field.field_name);
    
    // 根据字段类型定义数据类型
    if (isTimeField) {
        dataType = 'DATETIME';
    } else {
        switch (field.field_type) {
            case 'string':
                if (field.is_image || field.is_attachment) {
                    dataType = 'TEXT';
                } else if (field.field_code === 'id') {
                    dataType = 'VARCHAR(50)';
                    extraConstraints = ' UNIQUE';
                } else if (field.field_code === 'SeqNo') {
                    dataType = 'VARCHAR(50)';
                    extraConstraints = ' UNIQUE';
                } else {
                    dataType = 'VARCHAR(500)';
                }
                break;
            case 'json':
            case 'array':
            case 'object':
                dataType = 'JSON';
                break;
            case 'datetime':
                dataType = 'DATETIME';
                break;
            case 'integer':
                dataType = 'INT';
                break;
            case 'decimal':
                dataType = 'DECIMAL(10,2)';
                break;
            case 'boolean':
                dataType = 'TINYINT(1)';
                defaultValue = ' DEFAULT 0';
                break;
            default:
                dataType = 'TEXT';
        }
    }
    
    // 系统字段设置为非空
    if (field.is_system) {
        nullable = 'NOT NULL';
    }
    
    return `${columnName} ${dataType} ${nullable}${defaultValue}${extraConstraints} COMMENT ${comment}`;
}

// 生成索引
function generateIndexes(fields, tableName) {
    let sql = `-- 创建索引\n`;
    
    // 为系统字段创建索引
    const systemFields = fields.filter(f => f.is_system);
    systemFields.forEach(field => {
        if (['id', 'title', 'created_time'].includes(field.field_code)) {
            sql += `CREATE INDEX \`idx_${field.field_code}\` ON \`${tableName}\` (\`${field.field_code}\`);\n`;
        }
    });
    
    // 为日期字段创建索引
    const dateFields = fields.filter(f => f.field_type === 'datetime');
    dateFields.forEach(field => {
        sql += `CREATE INDEX \`idx_${field.field_code}\` ON \`${tableName}\` (\`${field.field_code}\`);\n`;
    });
    
    sql += `\n`;
    return sql;
}

// 生成查询示例
function generateQueryExamples(fields, tableName) {
    let sql = `-- ===========================================\n`;
    sql += `-- 查询示例\n`;
    sql += `-- ===========================================\n\n`;
    
    // 基本查询
    sql += `-- 查询所有数据\n`;
    sql += `-- SELECT * FROM \`${tableName}\` LIMIT 10;\n\n`;
    
    // 按条件查询
    const titleField = fields.find(f => ['title', 'F0000024'].includes(f.field_code));
    if (titleField) {
        sql += `-- 按标题查询\n`;
        sql += `-- SELECT * FROM \`${tableName}\` WHERE \`${titleField.field_code}\` LIKE '%关键词%';\n\n`;
    }
    
    // 按日期查询
    const dateFields = fields.filter(f => f.field_type === 'datetime');
    if (dateFields.length > 0) {
        const dateField = dateFields[0];
        sql += `-- 按日期范围查询\n`;
        sql += `-- SELECT * FROM \`${tableName}\` WHERE \`${dateField.field_code}\` >= '2024-01-01' AND \`${dateField.field_code}\` <= '2024-12-31';\n\n`;
    }
    
    // 统计查询
    sql += `-- 数据统计\n`;
    sql += `-- SELECT COUNT(*) as total_records FROM \`${tableName}\`;\n\n`;
    
    // 字段说明
    sql += `-- ===========================================\n`;
    sql += `-- 字段说明\n`;
    sql += `-- ===========================================\n`;
    fields.forEach(field => {
        const typeDesc = getFieldTypeDescription(field);
        sql += `-- ${field.field_code}: ${field.field_name} (${typeDesc})\n`;
    });
    
    return sql;
}

// 获取字段类型说明
function getFieldTypeDescription(field) {
    let desc = field.field_type;
    const tags = [];
    
    if (field.is_system) tags.push('系统字段');
    if (field.is_image) tags.push('图片字段');
    if (field.is_attachment) tags.push('附件字段');
    
    if (tags.length > 0) {
        desc += ' - ' + tags.join('、');
    }
    
    return desc;
}

// 显示生成结果
function showGenerationResult(fields, fileName) {
    const resultsDiv = document.getElementById('field-results');
    if (!resultsDiv) return;
    
    const systemCount = fields.filter(f => f.is_system).length;
    const businessCount = fields.filter(f => !f.is_system).length;
    const imageCount = fields.filter(f => f.is_image).length;
    const attachmentCount = fields.filter(f => f.is_attachment).length;
    
    const resultHtml = `
        <div class="generation-result" style="margin-top: 20px; padding: 20px; background-color: #e8f5e8; border: 1px solid #c8e6c9; border-radius: 6px;">
            <h4 style="color: #2e7d32; margin-bottom: 15px;">SQL文件生成成功</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 15px;">
                <div class="result-stat">
                    <strong>文件名称:</strong><br>
                    <code style="background: #f5f5f5; padding: 4px 8px; border-radius: 3px; word-break: break-all;">${fileName}</code>
                </div>
                <div class="result-stat">
                    <strong>字段统计:</strong><br>
                    总计 ${fields.length} 个（系统 ${systemCount} + 业务 ${businessCount}）
                </div>
                <div class="result-stat">
                    <strong>特殊字段:</strong><br>
                    图片 ${imageCount} 个，附件 ${attachmentCount} 个
                </div>
            </div>
            <div style="font-size: 14px; color: #555;">
                <p style="margin: 5px 0;">✓ 自动生成表结构、索引和查询示例</p>
                <p style="margin: 5px 0;">✓ 支持UTF8MB4编码，兼容表情符号</p>
                <p style="margin: 5px 0;">✓ 包含完整的字段注释和说明</p>
                <p style="margin: 5px 0;">✓ 可直接导入MySQL数据库使用</p>
            </div>
        </div>
    `;
    
    // 在表格后面添加结果显示
    const existingResult = resultsDiv.querySelector('.generation-result');
    if (existingResult) {
        existingResult.remove();
    }
    
    resultsDiv.insertAdjacentHTML('beforeend', resultHtml);
}

// 点击展开/收起示例值
function toggleSampleValue(element) {
    const fullValue = element.getAttribute('data-full-value');
    const currentText = element.textContent.trim();
    
    if (element.classList.contains('expanded')) {
        // 当前是展开状态，收起
        element.textContent = truncateText(fullValue, 30);
        element.classList.remove('expanded');
    } else {
        // 当前是收起状态，展开
        element.textContent = fullValue;
        element.classList.add('expanded');
    }
}

// 鼠标移除时收起示例值
function collapseSampleValue(element) {
    if (element.classList.contains('expanded')) {
        const fullValue = element.getAttribute('data-full-value');
        element.textContent = truncateText(fullValue, 30);
        element.classList.remove('expanded');
    }
}

// 筛选字段
function filterFields() {
    const filterValue = document.getElementById('field-filter').value;
    const rows = document.querySelectorAll('.field-table tbody tr');
    
    let visibleCount = 0;
    
    rows.forEach((row, index) => {
        const field = currentFieldData[index];
        if (!field) return;
        
        let shouldShow = false;
        
        switch(filterValue) {
            case 'all':
                shouldShow = true;
                break;
            case 'system':
                shouldShow = field.is_system;
                break;
            case 'main':
                shouldShow = !field.is_system && !field.is_child_table && !field.is_child_table_field;
                break;
            case 'main_image':
                shouldShow = !field.is_system && !field.is_child_table && !field.is_child_table_field && field.is_image;
                break;
            case 'main_attachment':
                shouldShow = !field.is_system && !field.is_child_table && !field.is_child_table_field && field.is_attachment;
                break;
            case 'child_table':
                shouldShow = field.is_child_table;
                break;
            case 'child_field':
                shouldShow = field.is_child_table_field;
                break;
            case 'child_image':
                shouldShow = field.is_child_table_field && field.is_image;
                break;
            case 'child_attachment':
                shouldShow = field.is_child_table_field && field.is_attachment;
                break;
        }
        
        if (shouldShow) {
            row.style.display = '';
            visibleCount++;
        } else {
            row.style.display = 'none';
            // 取消隐藏行的选中状态
            const checkbox = row.querySelector('.field-checkbox');
            if (checkbox) checkbox.checked = false;
        }
    });
    
    // 更新全选按钮状态
    handleFieldSelection();
    
    // 更新状态提示
    updateFieldStatus(`当前显示 ${visibleCount} 个字段`, 'success');
}

// 判断字段是否是图片字段
function isImageField(value, fieldCode) {
    // 1. 检查字段值是否是数组格式的图片数据
    if (Array.isArray(value)) {
        // 检查数组元素是否包含图片特征（URL、FileId等）
        if (value.length > 0 && typeof value[0] === 'object') {
            const firstItem = value[0];
            // 氚云图片字段通常包含 FileId, Url, FileName 等属性
            if (firstItem.FileId || firstItem.Url || firstItem.FileName) {
                return true;
            }
        }
    }
    
    // 2. 检查字段值是否是JSON字符串格式的图片数据
    if (typeof value === 'string' && value.trim().startsWith('[')) {
        try {
            const parsed = JSON.parse(value);
            if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0] === 'object') {
                const firstItem = parsed[0];
                if (firstItem.FileId || firstItem.Url || firstItem.FileName) {
                    return true;
                }
            }
        } catch (e) {
            // JSON解析失败，不是图片字段
        }
    }
    
    return false;
}

// 判断字段是否是附件字段
function isAttachmentField(value, fieldCode) {
    // 1. 检查字段值是否是数组格式的附件数据
    if (Array.isArray(value)) {
        // 检查数组元素是否包含附件特征
        if (value.length > 0 && typeof value[0] === 'object') {
            const firstItem = value[0];
            // 氚云附件字段通常包含 FileId, Url, FileName, FileSize 等属性
            // 与图片的区别可能在于文件扩展名或其他标识
            if (firstItem.FileId || firstItem.Url) {
                // 简单判断：如果有明确的附件标识，或者文件扩展名不是图片格式
                const fileName = firstItem.FileName || '';
                const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
                const isImage = imageExts.some(ext => fileName.toLowerCase().endsWith(ext));
                
                // 如果不是图片格式，认为是附件
                if (!isImage && fileName) {
                    return true;
                }
            }
        }
    }
    
    // 2. 检查字段值是否是JSON字符串格式的附件数据
    if (typeof value === 'string' && value.trim().startsWith('[')) {
        try {
            const parsed = JSON.parse(value);
            if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0] === 'object') {
                const firstItem = parsed[0];
                if (firstItem.FileId || firstItem.Url) {
                    const fileName = firstItem.FileName || '';
                    const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
                    const isImage = imageExts.some(ext => fileName.toLowerCase().endsWith(ext));
                    
                    if (!isImage && fileName) {
                        return true;
                    }
                }
            }
        } catch (e) {
            // JSON解析失败，不是附件字段
        }
    }
    
    return false;
}

// 生成主表
function generateMainTable(fields, tableName) {
    let sql = `-- 删除已存在的表\n`;
    sql += `DROP TABLE IF EXISTS \`${tableName}\`;\n\n`;
    
    sql += `-- 创建主表\n`;
    sql += `CREATE TABLE \`${tableName}\` (\n`;
    sql += `    \`auto_id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',\n`;
    
    fields.forEach((field, index) => {
        const columnDef = generateColumnDefinition(field);
        const comma = index === fields.length - 1 ? '' : ',';
        sql += `    ${columnDef}${comma}\n`;
    });
    
    sql += `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='氚云主数据表';\n\n`;
    
    return sql;
}

// 生成子表
function generateChildTable(fields, parentCode, mainTableName) {
    const childTableName = `${mainTableName}_${parentCode}`;
    
    let sql = `-- 删除已存在的子表\n`;
    sql += `DROP TABLE IF EXISTS \`${childTableName}\`;\n\n`;
    
    sql += `-- 创建子表: ${parentCode}\n`;
    sql += `CREATE TABLE \`${childTableName}\` (\n`;
    sql += `    \`child_id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '子表自增主键',\n`;
    sql += `    \`parent_id\` BIGINT NOT NULL COMMENT '关联主表ID',\n`;
    
    fields.forEach((field, index) => {
        // 移除字段代码中的父表前缀
        const cleanFieldCode = field.field_code.replace(`${parentCode}.`, '');
        // 修正字段名称，移除父表前缀
        const cleanFieldName = field.field_name.replace(`${parentCode}.`, '');
        const cleanField = {
            ...field, 
            field_code: cleanFieldCode,
            field_name: cleanFieldName
        };
        const columnDef = generateColumnDefinition(cleanField);
        const comma = index === fields.length - 1 ? '' : ',';
        sql += `    ${columnDef}${comma}\n`;
    });
    
    sql += `,\n    KEY \`idx_parent_id\` (\`parent_id\`),\n`;
    sql += `    CONSTRAINT \`fk_${childTableName}_parent\` FOREIGN KEY (\`parent_id\`) REFERENCES \`${mainTableName}\` (\`auto_id\`) ON DELETE CASCADE\n`;
    sql += `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='氚云子表: ${parentCode}';\n\n`;
    
    return sql;
}

// 生成视图
function generateViews(mainFields, childTables, mainTableName) {
    let sql = `-- ===========================================\n`;
    sql += `-- 创建视图（可选）\n`;
    sql += `-- ===========================================\n\n`;
    
    // 如果没有子表，不生成视图
    if (Object.keys(childTables).length === 0) {
        sql += `-- 无子表，跳过视图创建\n\n`;
        return sql;
    }
    
    sql += `-- 注意：视图仅用于查询，不建议直接插入数据\n\n`;
    
    return sql;
}